<?php
namespace app\admin\controller;
use think\Controller;
use think\request;
use  app\admin\model\Admin;
use think\Session;
use \traits\controller\Jump;
use think\Db;
class Login extends Controller
{
	/**
	 * 登录页视图
	 */
	public function index()
	{
		return $this->fetch();
	}

	public function verify()
	{

	}

	public function login(Request $request)
	{
		//echo $request->method();
		if($request->method()!="POST") halt('页面不存在');
		$captcha=new \think\captcha\Captcha();
		//dump($request->param('code'));
		if(!$captcha->check($request->param('code')))
		{
			return $this->error('验证码错误');
		}

		$account=$request->param('username');
		$pwd=md5($request->param('password'));
		$where=array('account'=>$account);
		//用数据库助手函数对输入的账号密码进行验证；
		//方式1：通过模型来完成对admin数据表的读取；
		$user=Admin::getByAccount($account);
		
		//方式2：通过数据库直接对数据表进行读取；
		// $db=db('admin');

		// $user=$db->where('account',$account)->select();

		if(!$user || $user['password']!=$pwd)
		{
			$this->error('账号或密码错误！');
		}

		if ($user['lock'])
		{
			$this->erroro('账号被锁定');
		}

		$user->logintime=time();
		$user->loginip=$request->ip();
		$user->save();
		Session::set('uid',$user->id);
		Session::set('uname',$user->account);
		Session::set('logintime',$user->logintime);
		Session::set('loginip',$user->loginip);
		
		return $this->redirect('index/index');


		//dump($list);
		


	}
	/**
	 * 异步验证管理员帐号
	 */
	Public function checkAccount (Request $request) {
		//if (!$this->isAjax()) halt('页面不存在');
		$account = $request->post('username');
		$where = array('account' => $account);

		if (Db::name('admin')->where($where)->select()) {
			echo 1;
		} else {
			echo 0;
		}
	}

	/**
	 * 异步验证密码
	 */
	Public function checkPwd (Request $request) {
		if (!var_export($request->isAjax(), true)) halt('页面不存在');
		$account = $request->post('username');
		$pwd = md5($request->post('password'));
		//echo $pwd;
		//echo $account;
		$list = Db::name('admin')->where('account',$account)->find();
		//dump($list);
		//echo $password->password;
		//echo ($list['password'] && $list['password'] == $pwd);
		if ($list['password'] && $list['password'] == $pwd) {
			echo 1;
		} else {
			echo 0;
		}
	}

	/**
	 * 异步验证验证码
	 */
	Public function checkVerify () {
		if (!$this->isAjax()) halt('页面不存在');

		if ($_SESSION['verify'] == $this->_post('code', 'md5')) {
			echo 1;
		} else {
			echo 0;
		}
	}


	/**
	 * 退出
	 */
	public function loginout()
	{
		return $this->redirect('login/index');
	}
}